package pre.bookcloud.java21.menu2;

import com.alibaba.fastjson2.JSON;
import java.awt.*;
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

/** 学生签到系统主界面 */
public class StudentSignSystem extends JFrame {
  private static final String DATA_FILE = "students_data.json";
  private List<Student> students;
  private Map<String, JButton> studentButtons;
  private JLabel titleLabel;

  // 学生姓名数据（根据图片中的姓名）
  private final String[] studentNames = {
    "张子牧", "那田放", "赵雅楠", "徐朝高", "徐诗尧", "汪子扬",
    "蒋利扬", "包浩鸣", "陈慕岩", "张子益", "谢梓辰", "王泽迪",
    "卜同学", "李泽宁", "褚奕宁", "薛智予", "曹羽墨", "方钧硕",
    "戴梓博", "马云恒", "徐晨菲", "徐国恩", "朱祥华", "朱蓓蕾"
  };

  public StudentSignSystem() {
    studentButtons = new HashMap<>();
    initializeStudents();
    initializeUI();
    loadData();
    updateButtonColors();
  }

  /** 初始化学生数据 */
  private void initializeStudents() {
    students = new ArrayList<>();
    for (int i = 0; i < studentNames.length; i++) {
      students.add(new Student(studentNames[i], String.format("STU%03d", i + 1)));
    }
  }

  /** 初始化用户界面 */
  private void initializeUI() {
    setTitle("学生签到系统");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    setResizable(false);

    // 创建主面板
    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
    mainPanel.setBackground(Color.WHITE);

    // 创建标题
    createTitle(mainPanel);

    // 创建功能按钮面板
    createFunctionButtons(mainPanel);

    // 创建学生按钮网格
    createStudentGrid(mainPanel);

    add(mainPanel);

    // 设置窗口属性
    pack();
    setLocationRelativeTo(null);

    // 设置窗口图标
    try {
      setIconImage(Toolkit.getDefaultToolkit().createImage(""));
    } catch (Exception e) {
      // 忽略图标设置错误
    }
  }

  /** 创建标题 */
  private void createTitle(JPanel parent) {
    String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
    titleLabel = new JLabel(today + "签到", SwingConstants.CENTER);
    titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
    titleLabel.setBorder(new EmptyBorder(0, 0, 20, 0));
    parent.add(titleLabel, BorderLayout.NORTH);
  }

  /** 创建功能按钮 */
  private void createFunctionButtons(JPanel parent) {
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
    buttonPanel.setBackground(Color.WHITE);
    buttonPanel.setBorder(new EmptyBorder(0, 0, 20, 0));

    // 今日签到按钮
    JButton todaySignButton = createStyledButton("今日签到");
    todaySignButton.addActionListener(e -> showTodaySignStatus());

    // 查看历史签到按钮
    JButton historyButton = createStyledButton("查看历史签到");
    historyButton.addActionListener(e -> showHistoryDialog());

    // 统计按钮
    JButton statisticsButton = createStyledButton("统计");
    statisticsButton.addActionListener(e -> showStatisticsDialog());

    buttonPanel.add(todaySignButton);
    buttonPanel.add(historyButton);
    buttonPanel.add(statisticsButton);

    parent.add(buttonPanel, BorderLayout.CENTER);
  }

  /** 创建学生按钮网格 */
  private void createStudentGrid(JPanel parent) {
    JPanel gridPanel = new JPanel(new GridLayout(4, 6, 10, 10));
    gridPanel.setBackground(Color.WHITE);
    gridPanel.setBorder(new EmptyBorder(20, 0, 0, 0));

    for (Student student : students) {
      JButton button = createStudentButton(student);
      studentButtons.put(student.getName(), button);
      gridPanel.add(button);
    }

    parent.add(gridPanel, BorderLayout.SOUTH);
  }

  /** 创建样式化按钮 */
  private JButton createStyledButton(String text) {
    JButton button = new JButton(text);
    button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
    button.setPreferredSize(new Dimension(120, 35));
    button.setBackground(new Color(240, 240, 240));
    button.setBorder(BorderFactory.createRaisedBevelBorder());
    button.setFocusPainted(false);

    // 添加鼠标悬停效果
    button.addMouseListener(
        new java.awt.event.MouseAdapter() {
          public void mouseEntered(java.awt.event.MouseEvent evt) {
            button.setBackground(new Color(220, 220, 220));
          }

          public void mouseExited(java.awt.event.MouseEvent evt) {
            button.setBackground(new Color(240, 240, 240));
          }
        });

    return button;
  }

  /** 创建学生按钮 */
  private JButton createStudentButton(Student student) {
    JButton button = new JButton(student.getName());
    button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
    button.setPreferredSize(new Dimension(80, 40));
    button.setBorder(BorderFactory.createRaisedBevelBorder());
    button.setFocusPainted(false);

    // 添加点击事件
    button.addActionListener(e -> toggleStudentSign(student));

    return button;
  }

  /** 切换学生签到状态 */
  private void toggleStudentSign(Student student) {
    if ("signed".equals(student.getSign_status())) {
      student.cancelSign();
      JOptionPane.showMessageDialog(
          this, student.getName() + " 已取消签到", "签到状态", JOptionPane.INFORMATION_MESSAGE);
    } else {
      student.signIn();
      JOptionPane.showMessageDialog(
          this, student.getName() + " 签到成功！", "签到状态", JOptionPane.INFORMATION_MESSAGE);
    }

    updateButtonColors();
    saveData();
  }

  /** 更新按钮颜色 */
  private void updateButtonColors() {
    for (Student student : students) {
      JButton button = studentButtons.get(student.getName());
      if (button != null) {
        if ("signed".equals(student.getSign_status())) {
          button.setBackground(new Color(144, 238, 144)); // 浅绿色
        } else {
          button.setBackground(new Color(240, 240, 240)); // 灰色
        }
      }
    }
  }

  /** 显示今日签到状态 */
  private void showTodaySignStatus() {
    StringBuilder message = new StringBuilder("今日签到状态：\n\n");
    int signedCount = 0;

    for (Student student : students) {
      if ("signed".equals(student.getSign_status())) {
        message.append("✓ ").append(student.getName()).append("\n");
        signedCount++;
      }
    }

    message.append("\n签到人数：").append(signedCount).append("/").append(students.size());

    JOptionPane.showMessageDialog(
        this, message.toString(), "今日签到", JOptionPane.INFORMATION_MESSAGE);
  }

  /** 显示历史签到对话框 */
  private void showHistoryDialog() {
    JOptionPane.showMessageDialog(this, "历史签到功能开发中...", "历史签到", JOptionPane.INFORMATION_MESSAGE);
  }

  /** 显示统计对话框 */
  private void showStatisticsDialog() {
    int signedCount = 0;
    for (Student student : students) {
      if ("signed".equals(student.getSign_status())) {
        signedCount++;
      }
    }

    String message =
        String.format(
            "统计信息：\n\n总学生数：%d\n已签到：%d\n未签到：%d\n签到率：%.1f%%",
            students.size(),
            signedCount,
            students.size() - signedCount,
            (double) signedCount / students.size() * 100);

    JOptionPane.showMessageDialog(this, message, "统计", JOptionPane.INFORMATION_MESSAGE);
  }

  /** 保存数据到JSON文件 */
  private void saveData() {
    try (FileWriter writer = new FileWriter(DATA_FILE)) {
      String jsonString = JSON.toJSONString(students);
      writer.write(jsonString);
    } catch (IOException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          this, "保存数据失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
    }
  }

  /** 从JSON文件加载数据 */
  private void loadData() {
    File file = new File(DATA_FILE);
    if (!file.exists()) {
      return;
    }

    try (FileReader reader = new FileReader(DATA_FILE)) {
      StringBuilder jsonContent = new StringBuilder();
      char[] buffer = new char[1024];
      int length;
      while ((length = reader.read(buffer)) != -1) {
        jsonContent.append(buffer, 0, length);
      }

      List<Student> loadedStudents = JSON.parseArray(jsonContent.toString(), Student.class);

      if (loadedStudents != null) {
        // 更新现有学生的签到状态
        for (Student loadedStudent : loadedStudents) {
          for (Student student : students) {
            if (student.getName().equals(loadedStudent.getName())) {
              student.setSign_status(loadedStudent.getSign_status());
              student.setSign_date(loadedStudent.getSign_date());
              student.setGen_date(loadedStudent.getGen_date());
              break;
            }
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          this, "加载数据失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
    }
  }

  /** 主方法 */
  public static void main(String[] args) {
    // 设置外观
    try {
      UIManager.setLookAndFeel(UIManager.getLookAndFeel());
    } catch (Exception e) {
      e.printStackTrace();
    }

    // 创建并显示界面
    SwingUtilities.invokeLater(
        () -> {
          new StudentSignSystem().setVisible(true);
        });
  }
}
